package swu.administrator;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.http.*;
import swu.filter.VeriFilter;
import swu.user.User;
import swu.verification.VeriCodeServlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class AdminLoginServlet extends HttpServlet
{
    private Map<String, User> users = new HashMap<>();

    public void init(ServletConfig config)
    {
        String userString = config.getInitParameter("users");
        String[] userAndPass = userString.split("@");
        User user = new User(userAndPass[0],userAndPass[1]);
        this.users.put(user.getName(),user);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        String name = request.getParameter("user");
        String pass = request.getParameter("pass");
        String code = request.getParameter("code");

        HttpSession session = request.getSession(true);
        String authcode = (String) session.getAttribute(VeriCodeServlet.AUTH_CODE);
        if (authcode == null || !authcode.equalsIgnoreCase(code))
        {
            response.sendRedirect("./index.html");
            return;
        }

        User user = this.users.get(name);
        if (user != null)
        {
            if (user.getPassword().equals(pass))
            {
                response.addCookie(new Cookie("shoppingMall-administrator", name));
                session = request.getSession(true);
                session.setAttribute(VeriFilter.LOGIN_TAG, VeriFilter.LOGIN_SUCCESS);

                response.sendRedirect("./administrator/list.html");
                return;
            }
        }

        response.sendRedirect("./index.html");
    }
}
